const { length } = require("../../../mybehaviors/location/location");

var app = getApp();

Page({
  data: {
    language: '',
    collectIndex:0,
    collectStoreIs:false,
    collectTabs:[
      {
        name:'商品',
        status:1,
      },
      {
        name:'商户',
        status:2,
      }
    ],
    commercialList:[],
    isLoadMore: true,
    page:1,
    totalPage:0,
    // goodsData:[],
    goodsData:[],
    dataState:0,
    showEdit:false,
    // 是否显示面板指示点
    indicatorDots: true,
    // 方向
    vertical: false, 
    // 是否自动切换 
    autoplay: true,
    // 自动切换时间间隔
    interval: 4000,
    // 滑动动画时长
    duration: 300,
    startPoint:'',
    slipFlag:'',
    checkAll:false,
    collChecked:false,
    collectIdArr:[],
    commIdArr:[], //商户
    iPnoneBottomBol:false
  },
  // 清空收藏收藏(没接口)
  claerData:function(){
    var that= this;
    var url = app.getNetAddresss("favorite/Remove");
    url += "&id="+e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除么？此操作不可逆！',
      success: function(res) {
        if (res.confirm) {
          app._getNetWork(
            {
              url:url,
              success:function(res){
                var _data = res.data;
                if(_data.result==1){
                  that._getData();
                  wx.showToast({
                    title: _data.msg,
                    icon: 'success',
                    duration: 2000,
                    success:function(){},
                    fail:function(){}
                  });
                }
                else{
                  wx.showToast({
                    title: '数据错误',
                    icon: 'success',
                    duration: 2000,
                    success:function(){},
                    fail:function(){}
                  });
                }
                
              },
              fail:function(res){}
            } 
          );
        }
      }
    });
  },
  myTouchStart(e) {
     //开启滑动事件
     this.setData({
      startPoint: e.touches[0]
     })
  },
  myTouchMove(e) {
    // ----------------监听手势左右滑事件----------------
    if (((this.data.startPoint.clientX - e.touches[e.touches.length - 1].clientX) > 80) && !this.data.slipFlag) {
          this.setData({
            slipFlag:true
          })
          return
      } else if (((this.data.startPoint.clientX - e.touches[e.touches.length - 1].clientX) < -80) && this.data.slipFlag) {
          this.setData({
            slipFlag:false
          })
          return
      }
      // ----------------监听手势左右滑事件end----------------
  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  touchEnd(e){
    this.setData({
        touchEnd:e.timeStamp
    })
  },
  operateOn() {
    this.setData({
      checkAll:!this.data.checkAll
    })
  },
  checkItem(event) { //选择删除
    let index = event.currentTarget.dataset.index;
    let collArr = this.data.goodsData;
    let collectIdArr = [];
    collArr[index].checked = !collArr[index].checked;
    collArr.map((item,index) => {
      if(item.checked) {
        collectIdArr.push(item.goods?.id || '');
      }
    })
    let allCheck = collArr.every((item) => item.checked);
    this.setData({
      goodsData:collArr,
      collectIdArr:collectIdArr,
      collChecked:allCheck
    })
  },
  commCheckItem(event) {
    let index = event.currentTarget.dataset.index;
    let collArr = this.data.commercialList;
    collArr[index].checked = !collArr[index].checked;
    let commIdArr = [];
    collArr.map((item,index) => {
      if(item.checked) {
        commIdArr.push(item.id || '');
      }
    })
    let allCheck = collArr.every((item) => item.checked);
    this.setData({
      commercialList:collArr,
      commIdArr:commIdArr,
      collChecked:allCheck
    })
  },
  //全选功能
  allCheckOn(event) {
    let goodsData = this.data.goodsData;
    let commercialList = this.data.commercialList;
    let collChecked = !this.data.collChecked;
    if(this.data.collectIndex === 0){
      goodsData.forEach((item,index) => {
        collChecked?item.checked = true:item.checked = false;
      });
    } else {
      commercialList.forEach((item,index) => {
        collChecked?item.checked = true:item.checked = false;
      });
    }
    this.setData({
      collChecked:collChecked,
      goodsData,
      commercialList
    })
  },
  delCollClick(event) {
    let goodsid = event.currentTarget.dataset.goodsid;
    this.delData(goodsid);
  },
  // 打开编辑(没接口)
  openEdit:function(){
    wx.showToast({title: '加载中..',icon: 'loading',duration: 1000,mask:true});
    var that = this;
    that.setData({
      showEdit:true
    });
  },
  // 关闭编辑(没接口)
  closeEdit:function(){
    wx.showToast({title: '加载中..',icon: 'loading',duration: 1000,mask:true});
    var that = this;
    that.setData({
      showEdit:false
    });
  },
  // 单条删除
  delData:function(goodsid){
    var that= this;
    let api = this.data.collectIndex === 0 ?"member.member-favorite.destroy":"plugin.coupon-store.frontend.collection.destroy";
    //todo, 无接口
    var url = app.getNetAddresss(api);
    let json = {};
    // url += "&goods_id="+goodsid;
    if(this.data.collChecked) {
      json.has_all = true;
    } else {
      if(this.data.collectIndex === 0) {
        this.data.collectIdArr.length == 0?json.goods_id = goodsid:json.goods_id = this.data.collectIdArr;
      } else {
        this.data.commIdArr.length == 0?json.store_id = goodsid:json.store_id = this.data.commIdArr;
      }
      
    }
    
    wx.showModal({
      title: '提示',
      content: '确定要取消收藏么？此操作不可逆！',
      success: function(res) {
        if (res.confirm) {
          app._postNetWork(
            {
              url:url,
              data:json,
              success:function(res){
                var _data = res.data;
                if(_data.result==1){
                  that._getData();
                  that.setData({
                    checkAll:false
                  })
                  if (wx.tempCqSwipeCell) {
                    wx.tempCqSwipeCell.setData({
                      prevBox: 0
                    });
                  }
                  wx.showToast({
                    title: _data.msg,
                    icon: 'success',
                    duration: 2000,
                    success:function(){},
                    fail:function(){}
                  });
                }
                else{
                  wx.showToast({
                    title: '数据错误',
                    icon: 'success',
                    duration: 2000,
                    success:function(){},
                    fail:function(){}
                  });
                }
                
              },
              fail:function(res){}
            } 
          );
        }
      }
    });
  },
  confrimOn() {
    if(this.data.collChecked) {
      this.delData();
    } else {
      if(this.data.collectIndex === 0) {
        this.data.collectIdArr.length > 0?this.delData():this.$toast('请选择商品');
      } else {
        this.data.commIdArr.length > 0?this.delData():this.$toast('请选择商品');
      }
    }
    
  },
  // 获取数据
  _getData:function(){
    var that = this;
    let urlStr = app.getNetAddresss("member.member-favorite.index");
    let json = {
      basic_info:1
    };
    if(app.globalData.store_alone_temp == 1) {
      // 开启企业独立模块
      urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.member.favorite-list");
    }
    app._getNetWork(
      {
        url:urlStr,
        data:json,
        showToastIn:false,
        success:function(res){
          var _data = res.data;
          let couponStore = _data.basic_info.plugin_setting?.coupon_store;
          console.log("收藏data", _data);
          if(_data.result==1){
            var _dataState;
            if(_data.data.length>0){
              _dataState=2;
            }
            else{
              _dataState=1;
            }
            if(Object.prototype.toString.call(couponStore) === '[object Object]') {
              that.setData({
                collectStoreIs: true
              });
              that.storeCollectList();
            }
            let collectData = _data.data;
            collectData.map((item,index) => {
              item.checked = false;
            });
            that.setData({
              goodsData:collectData,
              dataState:_dataState,
            });
          }
          else{
            wx.showToast({title: '数据错误',icon: 'success',duration: 2000});
          }
        },
        fail:function(res){}
      } 
    );
  },
  storeCollectList() {
    let that = this;
    let json = {
      basic_info:1
    };
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.collection.storeCollectList");
    app._getNetWork(
      {
        url:urlStr,
        data:json,
        showToastIn:false,
        success:function(res){
          let _data = res.data;
          console.log("收藏data", _data);
          if(_data.result==1){
            if(_data.basic_info.plugin_setting?.coupon_store) {
              let commercialData =  _data.data.data;
              commercialData.map((item,index) => {
                item.checked = false;
              });
              that.setData({
                collectStoreIs: true,
                commercialList: commercialData
              })
            }
          }
          else{
            wx.showToast({title: '数据错误',icon: 'success',duration: 2000});
          }
        },
        fail:function(res){}
      } 
    );
  },
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.totalPage) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.collection.storeCollectList");
      let json = {
        cstore_id:this.data.storeId,
        page: this.data.page,
        kwd:this.data.keyword
      };
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          list.forEach((item) => {
            item.checked = false
          })
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              verifierList : this.data.verifierList.concat(list),
            })
          } else {
            this.data.page = this.data.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  commercialTo(event) {
    let storeId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../../../packageF/consumption/commodity/commodity?storeId=${storeId}`,
    })
  },
  goDetail(event) {
    let goodsid = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/packageA/detail_v2/detail_v2?id=${goodsid}`
    });
  },
  onLoad:function(options){
    this.getiPnoneBottom();
    this._getData();
   
  },
  onStoreChange(event) { //切换商户
    this.setData({
      collectIndex: event.detail.name,
      checkAll:false,
      collChecked:false
    })
    this._getData();
  },
  onReady:function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  },
});





